#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <iostream>
#include <cstring>
#include <unistd.h>

using std::cout;
using std::endl;

int main(int argc, char* argv[])
{
    if(argc != 3)
    {
        cout << "[ERROR]: parameter miss" << endl;
        exit(1);
    }

    std::string  serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);

    // 创建套接字
    int sockfd = ::socket(AF_INET, SOCK_STREAM, 0);
    if(sockfd < 0)
    {
        cout << "[FATAL]: sockfd error";
        exit(1);
    }

    // 服务器信息填充
    struct sockaddr_in server;
    server.sin_family = AF_INET;
    server.sin_port = htons(serverport);
    ::inet_pton(AF_INET, serverip.c_str(), &server.sin_addr);

    // connect
    int n = ::connect(sockfd, (struct sockaddr*)&server, sizeof(server));
    if(n < 0)
    {
        cout << "[FATAL]: connect error" << endl;
        exit(1);
    }

    while(true)
    {
        std::string message;
        std::cout << "Enter#";
        std::getline(std::cin,message);

        write(sockfd, message.c_str(), sizeof(message));

        char echo_buffer[1024];
        n = read(sockfd, echo_buffer, sizeof(echo_buffer));
        if(n > 0)
        {
            echo_buffer[n] = 0;
            std::cout << echo_buffer << endl;
        }
        else 
        {
            cout << "[ERROR]; read error" << endl;
        }
    }

    ::close(sockfd);
    return 0;
}